package com.lin.servlet;


import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lin.service.BookServiceImpl;
import com.lin.service.IBookService;
import com.lin.utils.BaseServlet;
import com.lin.vo.Book;
import com.lin.vo.Cart;
import com.lin.vo.CartItem;
@WebServlet(name="CartServlet",urlPatterns={"/cartServlet"})
public class CartServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private IBookService bookService=new BookServiceImpl();
	public Cart getCart(HttpServletRequest request){
		/**
		 * 不管Session域中有没有该数据(尝试获取)
		 */
		Cart cart  = (Cart) request.getSession().getAttribute("cart");
		if(cart == null){
			cart=new Cart();
			/**
			 * 将购物车存入Session中
			 */
			request.getSession().setAttribute("cart", cart);
		}
		return cart;
	}
	public String addCart(HttpServletRequest request,HttpServletResponse response) throws IOException{
		/**
		 * 1.获取书本id属性
		 */
		String bookId = request.getParameter("bid");
		System.out.println(bookId);
		/**
		 * 2.获取书本总数量
		 */
		Integer count = Integer.parseInt(request.getParameter("count"));
		/**
		 * 3.将数据保存到购物项
		 */
		CartItem cartItem=new CartItem();
		cartItem.setCount(count);
		/**
		 * 4.调用service方法(查询数据)
		 */
		Book book = bookService.findByIdBook(bookId);
		cartItem.setBook(book);
		// 获取购物车对象,将购物车项目存入购物车中
		Cart cart = getCart(request);
		if(cart == null){
			request.setAttribute("msg", "亲,您还没购物捏,请先去购物~");
			return "/jsps/msg.jsp";
		}
		cart.addCart(cartItem);
		response.getWriter().println(true);
		return "change:/jsps/cart/list.jsp";
	}
		@SuppressWarnings("unused")
	public String partAddCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String bookId = request.getParameter("bid");
		System.out.println(bookId);
		Integer count = Integer.parseInt(request.getParameter("count"));
		System.out.println();
	/*	String count = request.getParameter("count");
		if(count == null){
			count = 1;
		}*/
		CartItem cartItem = new CartItem();
		cartItem.setCount(count);
		Book book = bookService.findByIdBook(bookId);
		cartItem.setBook(book);
		// 获取购物车对象,将购物车项目存入购物车中
		Cart cart = getCart(request);
		if (cart == null) {
			request.setAttribute("msg", "亲,您还没购物捏,请先去购物~");
			return "/jsps/msg.jsp";
		}
		cart.addCart(cartItem);
		response.getWriter().println(true);
		return "";
	
	}

	public String deleteCartItem(HttpServletRequest request,HttpServletResponse response){
		String bid = request.getParameter("bid");
		// 得到Cart对象
		Cart cart = getCart(request);
		// 调用移除的方法
		cart.removeCartItem(bid);
		return "change:/jsps/cart/list.jsp";
	}
	public String clearCart(HttpServletRequest request,HttpServletResponse response){
			Cart cart=getCart(request);
			cart.clearCart();
		return "change:/jsps/cart/list.jsp";
	}
}
